package com.xing.binbackend.pattern.proxy21.operation.audit;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;

// 3. 审计代理处理器
class AuditProxy implements InvocationHandler {
    private final Object target;
    private final String currentUser;
    private final PermissionService permissionService;

    public AuditProxy(Object target, String user) {
        this.target = target;
        this.currentUser = user;
        this.permissionService = new PermissionService();
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 权限校验
        if (!permissionService.checkPermission(currentUser, method.getName())) {
            throw new SecurityException("用户 " + currentUser + " 无权限执行此操作");
        }
        // 执行原始操作
        Object result = method.invoke(target, args);
        // 记录审计日志
        System.out.printf("[审计日志] 用户:%s | 操作:%s | 参数:%s | 时间:%tF %tT%n",
                currentUser, method.getName(), Arrays.toString(args),
                System.currentTimeMillis(), System.currentTimeMillis());
        return result;
    }
}
